package com.cjq.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author junqiancai@foxmail.com
 * @since 2021/6/10 12:09
 */
@Component
public class JwtUtils {
    private static String signSecret;//签名密钥

    public static final String AUTHENTICATION="Authorization";
    public static final Integer EXPIRE_TIME=1209600;    //单位秒(14天)
    public static final String REDIS_PREFIXED="token:";    //redis中token的key前缀

    /**
     * 从配置信息中读取jwt的签名密钥
     * @param signSecret 签名密钥
     */
    @Value("${diy.props.jwt-secret}")
    public void setSignatureSecret(String signSecret) {
        JwtUtils.signSecret = signSecret;
    }

    /**
     * 生成token  header.payload.signature
     * @return 返回token
     */
    public static String createJwtToken(Map<String,Object> map){
        Date createDate = new Date();
        Calendar now = Calendar.getInstance();
        now.add(Calendar.SECOND,EXPIRE_TIME);   //有效期一小时
        Date expireDate = now.getTime();
        //header
        HashMap<String,Object> header = new HashMap<>(4);
        header.put("alg","HS256");
        header.put("typ","JWT");
        return JWT.create()
                .withHeader(header)
                .withIssuedAt(createDate)
                .withExpiresAt(expireDate)
                .withSubject("这是一个jwt")
                .withClaim("id", (Integer) map.get("id"))
                .withClaim("username", (String) map.get("username"))
                .withClaim("userType", (Integer) map.get("userType"))
                .withClaim("realName", (String) map.get("realName"))
                .withClaim("role", (Integer) map.get("role"))
                .sign(Algorithm.HMAC256(signSecret));
    }

    /**
     * 验证token，成功返回decodedJWT，失败会抛异常
     * @param token
     * @return DecodedJWT 带有payload信息
     */
    public static DecodedJWT decodeJwt(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(signSecret)).build();
        return verifier.verify(token);
    }
}
